import {TranslateService} from '@ngx-translate/core';
import {Injectable} from '@angular/core';
import {en_GB, NzI18nService, zh_CN} from 'ng-zorro-antd';
import {Setting} from '../setting/setting';

@Injectable({
  providedIn: 'root'
})
export class MainService {

  constructor(public translate: TranslateService,
              private nzI18nService: NzI18nService) {
  }

  /**
   * support language
   */
  static getSupportLanguages() {
    return [{key: 'en_GB', val: '英文（English）'}, {key: 'zh_CN', val: '中文（Chinese）'}];
  }

  /**
   * 国际化语言支持
   */
  public languageSupport() {
    const languagesList = MainService.getSupportLanguages();
    const languages = languagesList.map(language => language.key); // Add language support where the language name is the same as the json file name
    this.translate.addLangs(languages);

    const defaultLanguage = 'en_GB';
    this.translate.setDefaultLang(defaultLanguage);

    const broswerLang = this.translate.getBrowserCultureLang().replace('-', '_');   // 获取当前浏览器环境的语言，浏览器语言用“-”拼接，需要转化
    const lastLanguage = localStorage.getItem(Setting.storage.language); // last language
    const languageRegExp = new RegExp(languages.join('|'));

    // Detects whether the language matches the supported language
    const lang = lastLanguage && lastLanguage.match(languageRegExp) && lastLanguage.match(languageRegExp)[0] ?
      lastLanguage.match(languageRegExp)[0] :
      broswerLang.match(languageRegExp) && broswerLang.match(languageRegExp)[0] ?
        broswerLang.match(languageRegExp)[0] :
        defaultLanguage;

    this.translate.use(lang).subscribe(data => {
      Setting.I18nData = data; // save data to an object, .ts files need it
    });
    localStorage.setItem(Setting.storage.language, lang); // save
    this.setZorroLanguage(lang); // set Zorro language

  }

  /**
   * set Zorro language
   * @param lang
   */
  setZorroLanguage(lang) {
    if (/en|en_GB|en_US/.test(lang)) { this.nzI18nService.setLocale(en_GB); }
    if (/zh|zh_CN/.test(lang)) { this.nzI18nService.setLocale(zh_CN); }
  }
}
